import axios from 'axios';
import { BASE_URL } from '../config';

const axiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

export const userApi = {
  login: async (credentials) => {
    // 验证邮箱登录
    if (credentials.email) {
      const response = await axiosInstance.get(`/users?email=${credentials.email}`);
      const users = response.data;
      const user = users[0];
      
      if (!user) {
        throw new Error('用户不存在');
      }

      if (user.password !== credentials.password) {
        throw new Error('密码错误');
      }

      // 检查用户状态
      if (user.status === 'inactive') {
        throw new Error('账号已被禁用，请联系管理员');
      }
      if (user.status === 'pending') {
        throw new Error('账号待验证，请查收邮件进行验证');
      }

      // 返回用户信息时排除敏感字段
      const { password, ...userWithoutPassword } = user;
      return { 
        user: userWithoutPassword,
        token: `mock-jwt-token-${Date.now()}` // 模拟返回token
      };
    }

    // 验证手机号登录
    if (credentials.phone) {
      const response = await axiosInstance.get(`/users?phone=${credentials.phone}`);
      const users = response.data;
      const user = users[0];
      
      if (!user) {
        throw new Error('用户不存在');
      }

      if (credentials.verificationCode !== '123456') { // 为演示设置固定验证码
        throw new Error('验证码错误');
      }

      // 检查用户状态
      if (user.status === 'inactive') {
        throw new Error('账号已被禁用，请联系管理员');
      }
      if (user.status === 'pending') {
        throw new Error('账号待验证，请查收邮件进行验证');
      }

      // 返回用户信息时排除敏感字段
      const { password, ...userWithoutPassword } = user;
      return { 
        user: userWithoutPassword,
        token: `mock-jwt-token-${Date.now()}` // 模拟返回token
      };
    }

    throw new Error('请输入邮箱或手机号');
  },

  register: async (userData) => {
    // 数据验证
    if (!userData.email || !userData.password || !userData.username) {
      throw new Error('请填写完整注册信息');
    }

    // 检查邮箱是否已存在
    const emailCheckResponse = await axiosInstance.get(`/users?email=${userData.email}`);
    if (emailCheckResponse.data.length > 0) {
      throw new Error('该邮箱已被注册');
    }
    
    // 检查手机号是否已存在
    if (userData.phone) {
      const phoneCheckResponse = await axiosInstance.get(`/users?phone=${userData.phone}`);
      if (phoneCheckResponse.data.length > 0) {
        throw new Error('该手机号已被注册');
      }
    }

    // 创建新用户
    const newUser = {
      ...userData,
      role: 'user',
      status: 'active',
      createTime: new Date().toISOString(),
      avatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png'
    };

    const response = await axiosInstance.post('/users', newUser);
    
    // 返回成功消息和用户信息（不包含密码）
    const { password, ...userWithoutPassword } = response.data;
    return { 
      message: '注册成功',
      user: userWithoutPassword
    };
  },

  logout: async () => {
    // 清除本地存储的登录状态
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    return { message: '退出成功' };
  },

  // 获取用户列表（仅供管理员使用）
  getUsers: async () => {
    const response = await axiosInstance.get('/users');
    // 返回用户列表时排除密码字段
    const usersWithoutPassword = response.data.map(user => {
      const { password, ...userWithoutPassword } = user;
      return userWithoutPassword;
    });
    return { users: usersWithoutPassword };
  },

  updateProfile: async (userId, profileData) => {
    const response = await axiosInstance.get(`/users/${userId}`);
    if (!response.data) {
      throw new Error('用户不存在');
    }

    // 更新用户信息
    const updatedResponse = await axiosInstance.patch(`/users/${userId}`, profileData);
    
    // 返回更新后的用户信息（不包含密码）
    const { password, ...userWithoutPassword } = updatedResponse.data;
    return { user: userWithoutPassword };
  },

  resetPassword: async (email) => {
    const response = await axiosInstance.get(`/users?email=${email}`);
    if (response.data.length === 0) {
      throw new Error('用户不存在');
    }

    const user = response.data[0];
    // 模拟重置密码
    const newPassword = Math.random().toString(36).slice(-8);
    await axiosInstance.patch(`/users/${user.id}`, { password: newPassword });

    return { message: '密码重置成功，新密码已发送到您的邮箱' };
  }
};